/*
 * Copyright (c) 2001-2010 Group JCDecaux. 17 rue Soyer, 92523 Neuilly Cedex,
 * France. All rights reserved.
 * 
 * This software is the confidential and proprietary information of Group
 * JCDecaux ("Confidential Information"). You shall not disclose such
 * Confidential Information and shall use it only in accordance with the terms
 * of the license agreement you entered into with Group JCDecaux.
 */
package com.excilys.ymca.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpMessage;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;

import android.util.Log;

public class RestUtil {

    private static final String TAG = RestUtil.class.getSimpleName();

    public static byte[] inputStreamAsByteArray(InputStream is) throws RuntimeException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte[] buffer = new byte[1024];
        int len;
        try {

            while ((len = is.read(buffer)) >= 0) {
                baos.write(buffer, 0, len);
            }

            return baos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static String inputStreamAsString(InputStream is, String contentEncoding) throws RuntimeException {
        byte[] ba = inputStreamAsByteArray(is);

        try {
            return new String(ba, contentEncoding);
        } catch (UnsupportedEncodingException e) {
            return new String(ba);
        }

    }

    public static InputStream inputStreamFromResponse(HttpResponse response) throws IOException {

        InputStream inputStream = response.getEntity().getContent();
        Header contentEncoding = response.getFirstHeader("Content-Encoding");
        if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
            inputStream = new GZIPInputStream(inputStream);
        }

        return inputStream;
    }

    public static void httpMessageAcceptsGzip(HttpMessage message) {
        message.addHeader("Accept-Encoding", "gzip");
    }

    public static String contentEncodingFromEntity(HttpEntity entity) {

        Header contentType = entity.getContentType();
        String contentEncoding = "UTF-8";

        for (HeaderElement element : contentType.getElements()) {
            NameValuePair pair = element.getParameterByName("charset");
            if (pair != null) {
                contentEncoding = pair.getValue();
                break;
            }
        }

        return contentEncoding;
    }

    public static InputStream logInputStream(InputStream result, String contentEncoding) throws RuntimeException {

        byte[] buf = RestUtil.inputStreamAsByteArray(result);

        ByteArrayInputStream loggedStream = new ByteArrayInputStream(buf);
        ByteArrayInputStream duplicatedStream = new ByteArrayInputStream(buf);

        Log.d(TAG, "Response:");
        Log.d(TAG, RestUtil.inputStreamAsString(loggedStream, contentEncoding));

        return duplicatedStream;
    }

}
